package cn.yhbk.web.modules.manager.Controller;

import cn.hutool.json.JSONObject;
import io.swagger.annotations.Api;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author pyrrhus
 */
@RestController
@RequestMapping("/api/ocr")
@Api(tags = "文字提取接口")
public class OCRController {

    private final RestTemplate restTemplate;

    public OCRController(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }

    @PostMapping
    public ResponseEntity<?> performOCR(@RequestBody List<String> imgUrls) {
        // 构建向 Python 服务的请求
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        JSONObject requestBody = new JSONObject();
        requestBody.put("img_paths", imgUrls);

        HttpEntity<String> request = new HttpEntity<>(requestBody.toString(), headers);

        // 发送请求到 Flask 服务
        String flaskServiceUrl = "http://localhost:5000/ocr";
        ResponseEntity<String> response = restTemplate.postForEntity(flaskServiceUrl, request, String.class);

        // 返回响应
        return ResponseEntity.ok(response.getBody());
    }
}